package com.stadsetjari_hi.Fragments;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;

import com.stadsetjari_hi.R;
import com.stadsetjari_hi.transmissionclasses.Asynctasks;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressLint("NewApi")
public class Loggin_Fragment extends Fragment implements OnClickListener {

	
	private EditText txtUserName, txtPassword;
	private android.app.FragmentManager fm;
	private Asynctasks connection;

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		connection = new Asynctasks(getActivity());
		View v = inflater.inflate(R.layout.v_login_frag, container, false);
		fm = getActivity().getFragmentManager();
		txtUserName = (EditText) v.findViewById(R.id.txtUserName);
		txtPassword = (EditText) v.findViewById(R.id.txtPassword);
		txtPassword.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
				if (arg1 == 66) {
					checklogin(txtUserName.getText().toString(), txtPassword.getText().toString());
					return true;
				}
				return false;
			}
		});
		Button btnLogin = (Button) v.findViewById(R.id.btnLogin);

		btnLogin.setOnClickListener(this);

		return v;
	}

	private void checklogin(String User, String pass) {
		boolean checklogin = false;
		
		try{
			checklogin = connection.checkLoginn(txtUserName.getText()
					.toString(), txtPassword.getText().toString());
		}
		catch(Exception e){
			Toast.makeText(getActivity(),
					"error, possible illegal charachter", 5).show();
			
		}
		if (checklogin == true) {
			Transmit_Location_Fragment TLFragment = new Transmit_Location_Fragment();
			TLFragment.setArguments(getActivity().getIntent().getExtras());

			android.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
				
			fragmentTransaction.setCustomAnimations(R.animator.slide_to_left,R.animator.slide_to_right);// R.animator.slide_to_right);
			fragmentTransaction.replace(R.id.myfragment, TLFragment);
			fragmentTransaction.commit();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnLogin:
			checklogin(txtUserName.getText().toString(), txtPassword.getText().toString());
			break;
		}
	}
}
